<!DOCTYPE html>
<html>

<head lang="en">
  <meta charset="UTF-8">
  <title>放大镜</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .box {
      width: 350px;
      height: 350px;
      margin: 100px;
      border: 1px solid #ccc;
      position: relative;
    }

    .big {
      width: 400px;
      height: 400px;
      position: absolute;
      top: 0;
      left: 360px;
      border: 1px solid #ccc;
      overflow: hidden;
      display: none;
    }

    .mask {
      width: 175px;
      height: 175px;
      background: rgba(255, 255, 0, 0.4);
      position: absolute;
      top: 0px;
      left: 0px;
      cursor: move;
      display: none;
    }

    .small {
      position: relative;
    }
  </style>
</head>

<body>
  <div class="box" id="box">
    <div class="small">
      <!--小层-->
      <img src="images/small.png" width="350" />
      <div class="mask"></div>
      <!--遮挡层-->
    </div>
    <!--小图-->
    <div class="big">
      <!--大层-->
      <img class="big_img" src="images/big.jpg" width="800" />
      <!--大图-->
    </div>
    <!--大图-->
  </div>
</body>

<script>
  // 大框
  let box = document.querySelector(".box");
  // 遮罩
  let min_wrap = document.querySelector(".mask");
  // 小图
  let min = document.querySelector(".small img");
  // 大图框
  let max_wrap = document.querySelector(".big");
  // 大图
  let max_img = document.querySelector(".big .big_img");

  // 鼠标进入
  box.onmouseenter = () => {
    max_wrap.style.display = "block";
    min_wrap.style.display = "block";
  }
  //鼠标离开
  box.onmouseleave = () => {
    max_wrap.style.display = "none";
    min_wrap.style.display = "none";
  }
  //鼠标移动
  box.onmousemove = e => {
    // 兼容
    var e = e || window.event;
    // 获取鼠标移动对x值 - 遮罩对一半 - 边框外对值
    let x = e.clientX - min_wrap.offsetWidth / 2 - box.offsetLeft;
    let y = e.clientY - min_wrap.offsetHeight / 2 - box.offsetTop;

    // 判断不要超出
    if (x < 0) {
      x = 0;
    } else if (x > box.clientWidth - min_wrap.offsetWidth) {
      x = box.clientWidth - min_wrap.offsetWidth;
    }

    if (y < 0) {
      y = 0;
    } else if (y > min.clientHeight - min_wrap.offsetHeight) {
      y = min.clientHeight - min_wrap.offsetHeight;
    }
    // 改变遮罩的位置
    min_wrap.style.left = x + "px";
    min_wrap.style.top = y + "px";

    // 控制大图的比例 大图/小图
    let xx = max_wrap.clientWidth / min_wrap.clientWidth;

    //改变大图的位置
    max_img.style.marginLeft = -x * xx + "px";
    max_img.style.marginTop = -y * xx + "px";
  }
</script>

</html>